<template>
  <div class="app-models-upload">
    <el-upload
      name="multipartFile"
      :action="uploadUrl"
      :http-request="upload"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :before-upload="handleBeforeUpload"
      :disabled="disabled"
      :multiple="multiple"
      :file-list="fileList">
      <el-button size="small" type="primary" :class="{'is-disabled': disabled}">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传{{ type }}类型文件</div>
    </el-upload>
  </div>
</template>

<script>
  import ApiClient from '@/utils/ApiClient';

  export default {
    name: "AppModelsUplaod",
    props: {
      value: null,
      nameProp: String, // 数组形式的数据要定义的文件名称字段
      urlProp: String, // 数组形式的数据要定义的文件链接字段
      fileName: { type: String, default: "" },
      multiple: { type: Boolean, default: false },
      type: { type: String, default: "obj,mtl,jpg" },
      disabled: { type: Boolean, default: false },
      required: { type: Boolean, default: false }
    },
    data() {
      return {
        uploadUrl: `/commons/attachments/uploadTmp.do`,
      }
    },
    computed: {
      fileList() {
        //if (!this.value) return []; // 当value值不存在
        let isArr = Array.isArray(this.value);
        let newArr = [];
        if (isArr) { // 上传的是多文件时 jpg
          newArr = this.value.map((file) => {
            return {
              name: file[this.nameProp],
              url: file[this.urlProp]
            }
          });
        } else { // 单文件上传时 obj ,mtl
          newArr = this.fileName && this.value
            ? [{ name: this.fileName, url: this.value }]
            : [];
        }
        return newArr;
      }
    },
    methods: {
      handleSuccess(resp,file,fileList) {
        let value = this.getValue(file);
        this.$emit('update:fileName',file.name);
        this.$emit('input',value);
      },

      handleBeforeUpload(file) {
        let ext = file.name.match(/\.([^.]+)$/); // 获取扩展名
        ext = ext ? ext[1].toLowerCase() : "";
        let hasExt = this.type.split(',').includes( ext ); // 判断文件格式
        if( !hasExt ){
          this.$message.error(`文件：${file.name}格式不正确`);
          return false;
        }
      },

      handleRemove(file,fileList) {
        let newValue = "";
        if( this.urlProp && Array.isArray(this.value) ){
          newValue = [...(this.value)].filter( (item) => item[this.urlProp] !== file.url );
        }
        this.$emit('input',newValue);
        this.$emit('update:fileName',"");
      },

      upload({action, filename, file, onSuccess}) {
        const form = new FormData();
        form.append(filename, file);
        ApiClient.post(action, form).then(onSuccess);
      },
      getValue(file) {
        // 多文件上传设置数组,单文件上传字符串
        if( this.urlProp && Array.isArray(this.value) ){
          return [
            ...( this.value ),
            {
              [this.urlProp]: file.response,
              [this.nameProp]: file.name
            }
          ]
        }else{
          return file.response
        }
      }

    }
  }
</script>

<style lang="scss" scoped>
  .el-upload__tip{
    margin-top: 5px;
    line-height: 1.5;
  }
  button.is-disabled{
    cursor: not-allowed;
  }

</style>
